# -*- encoding: utf-8 -*-

"""
@File:      tc_lzo_lzo_func_002.py
@Time:      2024/03/25 14:33:20
@Author:    chenchunhu
@Version:   1.0
@Contact:   wb-cch358909@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    chenchunhu
"""

from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_lzo_lzo_func_002.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """

    PARAM_DIC = {"pkg_name": "lzo lzo-devel gcc"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = '''cat >lzo_test2.c<<"EOF"
#include <stdio.h>
#include <stdlib.h>
#include <lzo/lzo1x.h>
#include <string.h>

// 确保这些长度足够大以容纳压缩和解压缩的数据
#define IN_LEN  (64*1024L) // 您可以调整这个值来测试不同数据长度下的压缩率
#define OUT_LEN (IN_LEN + IN_LEN / 16 + 64 + 3)

int main() {
    if (lzo_init() != LZO_E_OK) {
        printf("lzo_init() failed\\n");
        return 1;
    }

    unsigned char *in = malloc(IN_LEN);
    unsigned char *out = malloc(OUT_LEN);
    lzo_voidp wrkmem = malloc(LZO1X_1_MEM_COMPRESS);

    if (in == NULL || out == NULL || wrkmem == NULL) {
        printf("Failed to allocate memory\\n");
        return 1;
    }

    // 填充测试数据
    for (int i = 0; i < IN_LEN; i++) {
        in[i] = (unsigned char)(rand() & 0xFF);
    }

    lzo_uint out_len = OUT_LEN;
    int r = lzo1x_1_compress(in, IN_LEN, out, &out_len, wrkmem);

    if (r != LZO_E_OK) {
        printf("Compression failed: %d\\n", r);
        free(in);
        free(out);
        free(wrkmem);
        return 1;
    }

    // 计算并显示压缩率
    double compress_ratio = 100.0 * out_len / IN_LEN;
    printf("Original size: %lu bytes\\n", (unsigned long)IN_LEN);
    printf("Compressed size: %lu bytes\\n", (unsigned long)out_len);
    printf("Compression ratio: %.2f%%\\n", compress_ratio);

    // 清理工作
    free(in);
    free(out);
    free(wrkmem);

    return 0;
}
EOF'''
        self.cmd(cmdline)


    def test(self):
        self.cmd("gcc -o lzo_test2 lzo_test2.c -llzo2")
        code, lzo_result = self.cmd("./lzo_test2")
        self.assertIn("Original size: 65536 bytes", lzo_result)
        self.assertIn("Compressed size: 65797 bytes", lzo_result)
        self.assertIn("Compression ratio: 100.40%", lzo_result)

    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf lzo_test2.c lzo_test2")
